<template>
	<a-modal v-bind="options" class="bill-edit-dialog">
		<a-form :model="detail" ref="formRef">
			<vxe-grid ref="grid" :data="(detail.billDetailList as any[])" :loading="loadings.detail" v-bind="gridOptions">
				<template #feeSubjectValue="{row, rowIndex}">
					<template v-if="row.id">
						{{ row.feeSubjectValue }}
					</template>
					<a-form-item v-else :name="['billDetailList', rowIndex, 'feeSubjectId']" required has-feedback>
						<template #help />
						<a-select
							v-model:value="row.feeSubjectId"
							:options="costTypes"
							show-search
							option-filter-prop="name"
							:field-names="{label: 'name', value: 'id', options: 'metaList'}"
							placeholder="请选择费用科目" />
					</a-form-item>
				</template>
				<template #originalMoney="{row, rowIndex}">
					<a-form-item
						:name="['billDetailList', rowIndex, 'originalMoney']"
						:rules="[{required: true, type: 'number'}]"
						has-feedback>
						<template #help />
						<!-- 修改应收付金额≥已收付金额 -->
						<a-input-number
							v-model:value="row.originalMoney"
							:disabled="row.isOccur === 1"
							:precision="2"
							placeholder="请输入金额"
							style="width: 100%"
							@blur="(e:any) => onblur(e, rowIndex)">
							<template #prefix>
								<span v-color="{color: amountColor(row)}">{{ amountSymbol(row) }}</span>
							</template>
						</a-input-number>
					</a-form-item>
				</template>
				<template #action="{row, rowIndex}">
					<a-button
						type="link"
						size="small"
						danger
						v-if="!(detail.billDetailList && detail.billDetailList[rowIndex].occurredMoney)"
						@click="removeBill(rowIndex)">
						删除
					</a-button>
				</template>
				<template #bottom>
					<vxe-toolbar perfect>
						<template #buttons>
							待收(付) 总计
							<span v-color="{color: 'primary'}">&nbsp;{{ notOccurredMoney.toLocaleString() }}</span>
							&nbsp;元
						</template>
						<template #tools>
							<a-button type="link" size="small" @click="addBill(1)">
								<template #icon>
									<plus-square-outlined />
								</template>
								添加收款项
							</a-button>
							<a-button type="link" danger size="small" @click="addBill(2)">
								<template #icon>
									<minus-square-outlined />
								</template>
								添加付款项
							</a-button>
						</template>
					</vxe-toolbar>
				</template>
			</vxe-grid>

			<a-typography-text strong>
				<blockquote>支付详情</blockquote>
			</a-typography-text>
			<a-row :gutter="24">
				<a-col :span="12">
					<a-form-item label="客户姓名" name="payerName" :rules="[{required: true, message: '请输入客户姓名'}]">
						<a-input placeholder="请输入客户姓名" v-model:value="detail.payerName" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item
						label="客户电话"
						name="payerPhone"
						:rules="[{required: true, validator: 2 === contractType ? validateTel : validatePhone}]">
						<a-input placeholder="请输入客户电话" v-model:value="detail.payerPhone" :maxlength="2 === contractType ? 13 : 11" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item name="predictTime" label="支付时间" :rules="[{required: true, message: '请选择支付时间'}]">
						<a-date-picker v-model:value="detail.predictTime" :value-format="DATE_FORMAT.DATE" />
					</a-form-item>
				</a-col>
				<a-col :span="10">
					<a-form-item name="billCycle" label="账单周期" :rules="[{required: true, message: '请选择账单周期'}]">
						<a-range-picker :disabled="editable" v-model:value="detail.billCycle" :value-format="DATE_FORMAT.DATE" @change="handleChange"/>
					</a-form-item>
				</a-col>
				<a-col :span="2" v-action="['mk_finance_contract-bill_bjzdzq']">
					<EditOutlined v-if="editable" @click="changeEditAble(true)"/>
					<a-button  v-if="!editable" @click="changeEditAble(false)">保存</a-button>
				</a-col>
			</a-row>
			<a-form-item label="账单备注" name="comment">
				<a-textarea v-model:value="detail.comment" show-count :maxlength="200" placeholder="请输入账单备注" />
			</a-form-item>
			<a-form-item label="账单凭证">
				<file-upload :biz-id="id" show-qr-code show-tips />
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script setup lang="ts">
	import {computed, reactive, ref, toRef, watchEffect, watch} from 'vue'
	import {MinusSquareOutlined, PlusSquareOutlined, EditOutlined} from '@ant-design/icons-vue'
	import {VxeGridInstance, VxeGridProps} from 'vxe-table'
	import {Img} from 'yuxin-base/src/types'
	import {DIC_LABEL_MAP} from 'yuxin-base/src/constant'
	import {BillDeatil} from '@/interface/bill'
	import {getFinanceByBillId, updateFinanceAndDetail} from '@/api/bill'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import FileUpload from '@/components/common/file-upload.vue'
	import DATE_FORMAT from 'yuxin-base/src/utils/date'
	import {amountColor, amountSymbol} from 'yuxin-base/src/utils'
	import {FormInstance, message} from 'ant-design-vue'
	import {validatePhone, validateTel} from '@/utils/formValidation'

	const props = defineProps<{
		// 账单id
		id?: string
		visible: boolean
	}>()
	/** 当前选中的合同类型 1 个人 2 企业 */
	const contractType = ref<number | null>(1)
	const loadings = reactive({
		detail: false
	})
	const files = ref<Img[]>([])
	const detail = ref<BillDeatil>({
		billDetailList: []
	})
	const editable = ref(true)
	const changeEditAble = (visible) => {
		editable.value = !visible
	}
	const emits = defineEmits(['update:visible', 'close'])
	const options = reactive({
		title: '账单编辑',
		width: 1200,
		centered: true,
		maskClosable: false,
		destroyOnClose: true,
		confirmLoading: false,
		visible: toRef(props, 'visible'),
		onOk() {
			submit()
		},
		onCancel() {
			emits('update:visible', false)
			setTimeout(() => emits('close'), 100)
			files.value = []
			detail.value = {}
			deleteIds.value = []
			formRef.value?.resetFields()
		}
	})

	// 逻辑变更 保存被删除的id
	const deleteIds = ref<any>([])

	const costTypes = ref<any[]>([])
	watch(
		() => [props.visible, props.id],
		() => {
			if (props.visible && props.id) {
				getDetailById()
			}
		}
	)
	// watchEffect(() => {
	// 	if (props.visible && props.id) {
	const getDetailById = () => {
		settingApi.getDicListByLabel(DIC_LABEL_MAP['FEESUBJECT']).then(({data}) => {
			costTypes.value = data.filter(v => !!v.metaList.length)
		})

		loadings.detail = true
		getFinanceByBillId(props.id)
			.then(({data}) => {
				console.log('data===', data)
				detail.value = data
				detail.value.billCycle = [data.beginTime, data.endTime]
				contractType.value = data?.enterContractId ? 2 : 1
			})
			.finally(() => (loadings.detail = false))
	}
	// 	}
	// })

	const grid = ref<VxeGridInstance>()
	const gridOptions = reactive<VxeGridProps>({
		size: 'small',
		height: 300,
		showOverflow: true,
		rowConfig: {
			isHover: true
		},
		columns: [
			{
				title: '费用科目',
				minWidth: 200,
				slots: {
					default: 'feeSubjectValue'
				}
			},
			{
				title: '应收(付)',
				minWidth: 200,
				slots: {
					default: 'originalMoney'
				}
			},
			{
				title: '已收(付)',
				field: 'occurredMoney',
				minWidth: 200
			},
			{
				title: '待收(付)',
				field: 'notOccurredMoney',
				minWidth: 200
			},
			{
				title: '操作',
				width: 100,
				align: 'center',
				fixed: 'right',
				slots: {
					default: 'action'
				}
			}
		]
	})

	/**
	 * 添加账单
	 * @param feeDirection 费用方向【1收入2支出】
	 */
	const addBill = (feeDirection: number) => {
		const bill = {
			//原始金额【预计费用金额】
			originalMoney: null,
			//是否已发生【0预计发生1实际发生】
			isOccur: 0,
			feeSubjectValue: null,
			feeDirection,
			notOccurredMoney: 0,
			occurredMoney: 0
		}

		detail.value.billDetailList?.push(bill)
		grid.value?.loadData(detail.value.billDetailList as any[])
	}

	const removeBill = (index: number) => {
		// 删除逻辑修改 已落库的账单（存在id） 需求掉接口 前端新增的不需要
		if (detail.value.billDetailList && detail.value.billDetailList[index].id) {
			// 判断不为最后一条有id的账单 最后一条不给删
			let length = detail.value.billDetailList.filter(e => e.id).length
			// console.log('billDetailList长度', length)
			if (length <= 1) {
				message.warning('至少保留一个账单明细')
				return
			}

			let id = detail.value.billDetailList[index].id
			deleteIds.value.push(id)
			const formData = new FormData()
			formData.append('deleteReason', '删除')
		}

		detail.value.billDetailList?.splice(index, 1)
		grid.value?.loadData(detail.value.billDetailList as any[])
	}

	const notOccurredMoney = computed(() => {
		const list = detail.value.billDetailList || []
		const total = list.reduce(
			(prev, cur) => {
				prev.notOccurredMoney += cur.notOccurredMoney * (cur.feeDirection === 1 ? 1 : -1)
				return prev
			},
			{notOccurredMoney: 0}
		)
		return Number(total.notOccurredMoney.toFixed(2))
	})

	const onblur = (e: any, index: any) => {
		console.log('onblur', e, e.target.value)
		let value = e.target.value

		if (detail.value.billDetailList) {
			let data = detail.value.billDetailList[index]

			// 超出金额的话修改为待收付金额
			if (data.originalMoney >= Number(9999999999)) {
				data.originalMoney = data.notOccurredMoney
				message.error('总金额超出999999999.99，请检查输入金额')
				return
			}

			if (data.originalMoney < data.occurredMoney) {
				// 应收付金额 ≥ 已收付金额
				if (data.occurredMoney) {
					data.originalMoney = data.occurredMoney
					value = data.occurredMoney
				}
				message.warning('修改金额不可低于已收（付）金额' + data.occurredMoney + '元')
			}

			if (data.originalMoney < data.hasInvoicingMoney) {
				message.warning('修改金额不可低于已开发票金额' + data.hasInvoicingMoney + '元')
			}

			// 待收(付) 随 应收(付)改变
			data.notOccurredMoney = Number(value - data.occurredMoney).toFixed(2)
		}
	}

	// 确认
	const formRef = ref<FormInstance>()
	const submit = () => {
		if(!editable.value) {
			message.error('账单周期未保存')
			return
		}
		formRef.value?.validate().then(async () => {
			if (notOccurredMoney.value > Number(999999999)) {
				message.error('总金额超出999999999.99，请检查输入金额')
				return
			}

			const rawValue = detail.value,
				billCycle = rawValue.billCycle || []

			const data = {
				billId: rawValue.id,
				beginTime: billCycle[0],
				endTime: billCycle[1],
				comment: rawValue.comment,
				payerName: rawValue.payerName,
				payerPhone: rawValue.payerPhone,
				paymentAccount: rawValue.paymentAccount,
				paymentAccountType: rawValue.paymentAccountType,
				predictTime: rawValue.predictTime,
				billDetailFormList: rawValue.billDetailList,
				// 删除id合集
				removeBillDetailIds: deleteIds.value
			}

			options.confirmLoading = true
			updateFinanceAndDetail(data)
				.then(() => {
					options.onCancel()
					message.success('操作成功')
				})
				.finally(() => (options.confirmLoading = false))
		})
	}
</script>

<style lang="less">
	.bill-edit-dialog {
		.ant-modal-body {
			overflow: auto;
			min-height: 600px;
			max-height: 900px;
			padding: 16px 16px 0;

			.ant-form-item-label {
				width: 120px;
			}
		}
	}
</style>
